package com.crud.config;

import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hyh
 * @date 2023/06/20 19:11:01
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResultVo f1(Exception e){
        e.printStackTrace();
        return ResultVo.failure("出错了！",e.toString());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVo f2(MethodArgumentNotValidException e){
        e.printStackTrace();
        List<FieldError> errors = e.getBindingResult().getFieldErrors();
        Map<String, String> map = new HashMap<>();
        for (FieldError error : errors) {
            map.put(error.getField(), error.getDefaultMessage());
        }
        return ResultVo.failure("输入不正确", map);
    }
}
